package com.boot.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boot.constants.RedisKeys;
import com.boot.constants.StatusConstants;
import com.boot.entity.Comment;
import com.boot.entity.Question;
import com.boot.entity.Tag;
import com.boot.service.ICommentService;
import com.boot.service.IQuestionService;
import com.boot.service.ITagService;
import com.boot.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class AdminReviewNotificationTask {

    @Resource
    private IQuestionService questionService;

    @Resource
    private ICommentService commentService;

    @Resource
    private ITagService tagService;

    @Resource
    private MailService mailService;

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    @Value("${spring.mail.username}")
    private String adminEmail;

    /**
     * 每隔 2 分钟执行一次（不要太频繁，防止打扰管理员）
     */
    @Scheduled(fixedDelay = 2_000)
    public void scanAndNotifyPendingReviews() {
        log.info("[定时任务] 开始扫描待审批的问题与评论...");

        try {
            // 1. 处理待审批问题
            handlePendingQuestions();

            // 2. 处理待审批评论
            handlePendingComments();
        } catch (Exception e) {
            log.error("【通知任务异常】" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 扫描所有待审核问题，未通知过的发送提醒
     */
    private void handlePendingQuestions() {
        QueryWrapper<Question> wrapper = new QueryWrapper<>();
        wrapper.eq("status", StatusConstants.QuestionStatus.PENDING_REVIEW);
        List<Question> pendingQuestions = questionService.list(wrapper);

        for (Question q : pendingQuestions) {
            String idKey = String.valueOf(q.getId());

            // 检查是否已经发过通知
            Boolean hasNotified = redisTemplate.opsForSet().isMember(RedisKeys.SENT_QUESTION_NOTIFY, idKey);
            if (Boolean.TRUE.equals(hasNotified)) {
                continue; // 已通知，跳过
            }

            // 查询问题类型
            QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();
            tagQueryWrapper.eq("id", q.getType());
            Tag tag = tagService.getOne(tagQueryWrapper);
            if (tag != null) {
                q.setType(tag.getName());
            }

            // 发送邮件提醒
            sendQuestionReviewReminder(q);

            // 标记为已通知
            redisTemplate.opsForSet().add(RedisKeys.SENT_QUESTION_NOTIFY, idKey);
        }
    }

    /**
     * 扫描所有待审核评论，未通知过的发送提醒
     */
    private void handlePendingComments() {
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("status", StatusConstants.CommentStatus.PENDING);
        List<Comment> pendingComments = commentService.list(wrapper);

        for (Comment c : pendingComments) {
            String idKey = String.valueOf(c.getId());

            Boolean hasNotified = redisTemplate.opsForSet().isMember(RedisKeys.SENT_COMMENT_NOTIFY, idKey);
            if (Boolean.TRUE.equals(hasNotified)) {
                continue;
            }

            sendCommentReviewReminder(c);

            redisTemplate.opsForSet().add(RedisKeys.SENT_COMMENT_NOTIFY, idKey);
        }
    }

    /**
     * 发送问题审核提醒邮件
     */
    private void sendQuestionReviewReminder(Question q) {
        try {
            String subject = "🔔 新问题待审批 [#Q" + q.getId() + "]：" + truncate(q.getTitle(), 40);
            String content = buildQuestionEmailContent(q);
            mailService.sendHtmlMail(adminEmail, subject, content);
            log.info("✅ 已发送问题审批提醒邮件，ID=" + q.getId());
        } catch (Exception e) {
            log.error("📧 邮件发送失败（问题ID=" + q.getId() + "）：" + e.getMessage());
        }
    }

    /**
     * 发送评论审核提醒邮件
     */
    private void sendCommentReviewReminder(Comment c) {
        try {
            String subject = "💬 新评论待审批 [#C" + c.getId() + "]";
            String content = buildCommentEmailContent(c);
            mailService.sendHtmlMail(adminEmail, subject, content);
            log.info("✅ 已发送评论审批提醒邮件，ID=" + c.getId());
        } catch (Exception e) {
            log.error("📧 邮件发送失败（评论ID=" + c.getId() + "）：" + e.getMessage());
        }
    }

    // ==================== 邮件内容构建 ====================

    /**
     * 构建问题审核提醒邮件内容（Java 8 + 简洁拼接）
     */
    private String buildQuestionEmailContent(Question q) {
        return "<div style='font-family: Helvetica Neue, Arial, sans-serif; max-width: 600px; margin: 20px auto; background: #ffffff; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); overflow: hidden;'>"
                    + "<div style='background: linear-gradient(135deg, #1976D2, #1565C0); padding: 20px; text-align: center; color: white;'>"
                        + "<h2 style='margin: 0; font-size: 18px; font-weight: 600;'>📋 新问题待审批</h2>"
                        + "<p style='margin: 8px 0 0; opacity: 0.9; font-size: 14px;'>您有一条新的待处理问题</p>"
                    + "</div>"
                    + "<div style='padding: 20px; color: #333;'>"
                        + "<table width='100%' cellpadding='8'>"
                            + "<tr>"
                                + "<td width='30%' style='font-weight: bold; color: #444;'>问题编号</td>"
                                + "<td>" + q.getId() + "</td>"
                            + "</tr>"
                            + "<tr>"
                                + "<td style='font-weight: bold; color: #444;'>标题</td>"
                                + "<td>" + escapeHtml(q.getTitle()) + "</td>"
                            + "</tr>"
                            + "<tr>"
                                + "<td style='font-weight: bold; color: #444;'>类型</td>"
                                + "<td><span style='color: #1976D2; background: #e3f2fd; padding: 4px 8px; border-radius: 4px; font-size: 13px;'>"
                                + escapeHtml(q.getType())
                                + "</span></td>"
                            + "</tr>"
                            + "<tr>"
                                + "<td style='font-weight: bold; color: #444;'>描述</td>"
                                + "<td style='word-wrap: break-word;'>" + truncate(escapeHtml(q.getDescription()), 150) + "...</td>"
                            + "</tr>"
                            + "<tr>"
                                + "<td style='font-weight: bold; color: #444;'>提交时间</td>"
                                + "<td>" + q.getCreatedAt() + "</td>"
                            + "</tr>"
                        + "</table>"
                    + "</div>"
                    + "<div style='text-align: center; padding: 16px; font-size: 12px; color: #aaa; border-top: 1px solid #eee; background: #fafafa;'>"
                        + "&copy; " + java.time.LocalDate.now().getYear() + " 系统管理平台 · 请及时处理以保障服务效率"
                    + "</div>"
                + "</div>";
    }

    /**
     * 构建评论审核提醒邮件内容（Java 8 + 简洁拼接）
     */
    private String buildCommentEmailContent(Comment c) {
        return "<div style='font-family: Helvetica Neue, Arial, sans-serif; max-width: 600px; margin: 20px auto; background: #ffffff; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); overflow: hidden;'>"
                    + "<div style='background: linear-gradient(135deg, #FF9800, #F57C00); padding: 20px; text-align: center; color: white;'>"
                        + "<h2 style='margin: 0; font-size: 18px; font-weight: 600;'>🗨️ 新评论待审批</h2>"
                        + "<p style='margin: 8px 0 0; opacity: 0.9; font-size: 14px;'>您有一条新的待审核评论</p>"
                    + "</div>"
                    + "<div style='padding: 20px; color: #333;'>"
                        + "<table width='100%' cellpadding='8'>"
                            + "<tr>"
                                + "<td width='30%' style='font-weight: bold; color: #444;'>评论编号</td>"
                                + "<td>" + c.getId() + "</td>"
                            + "</tr>"
                            + "<tr>"
                                + "<td style='font-weight: bold; color: #444;'>所属问题ID</td>"
                                + "<td><span style='color: #FF9800; background: #fff3e0; padding: 4px 8px; border-radius: 4px; font-size: 13px;'>"
                                + c.getQuestionId()
                                + "</span></td>"
                            + "</tr>"
                            + "<tr>"
                                + "<td style='font-weight: bold; color: #444;'>用户ID</td>"
                                + "<td>" + c.getUserId() + "</td>"
                            + "</tr>"
                            + "<tr>"
                                + "<td style='font-weight: bold; color: #444;'>内容</td>"
                                + "<td style='word-wrap: break-word;'>" + truncate(escapeHtml(c.getContent()), 150) + "...</td>"
                            + "</tr>"
                            + "<tr>"
                                + "<td style='font-weight: bold; color: #444;'>提交时间</td>"
                                + "<td>" + c.getCreatedAt() + "</td>"
                            + "</tr>"
                        + "</table>"
                    + "</div>"
                    + "<div style='text-align: center; padding: 16px; font-size: 12px; color: #aaa; border-top: 1px solid #eee; background: #fafafa;'>"
                        + "&copy; " + java.time.LocalDate.now().getYear() + " 系统管理平台 · 请及时处理以保障社区质量"
                    + "</div>"
                + "</div>";
    }

    // ==================== 工具方法 ====================

    private String truncate(String str, int len) {
        if (str == null) return "";
        return str.length() <= len ? str : str.substring(0, len) + "...";
    }

    private String escapeHtml(String str) {
        if (str == null) return "";
        return str.replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#x27;");
    }
}
